package com.qf.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 全局 登录 过滤器    实现 GlobalFilter 才能是全局过滤器
 *
 * **需求：模拟一个登录的校验。基本逻辑：如果请求中有token参数，则认为请求有效，放行;如果没有拦截返回http 401。**
 * @author lixu
 */
@Component //实例化
public class GlobalLoginFilter implements GlobalFilter, Ordered {
    /**
     * 模拟一个登录的校验
     * @param exchange ： 服务器交换机  WebFlux 服务器
     * @param chain  过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1:请求
        ServerHttpRequest request = exchange.getRequest();
        //1.1 Cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        //  cookie: o2State={41324124412,12341243124,12341324123,213412413241}
        HttpCookie cookie = cookies.getFirst("csn");
        if(null != cookie)
           System.out.println("value:" + cookie.getValue());
        //1.2 Header
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        List<String> accept = headers.get("accept");
        //image/avif ,image/webp, image/apng,image/svg+xml,image/*,*/*;q=0.8
        //1.3 请求参数  http://localhost:10010/search/find?token=rrwewrqwrqwe&haha=hoho&h=uu
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String token1 = queryParams.getFirst("token");

        if(token1 != null){
            //假设有放行
            //放行
            return chain.filter(exchange);
        }else{
            //2：响应
            ServerHttpResponse response = exchange.getResponse();
            // 如果没有拦截返回http 401。
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//完成响应
        }

    }

    /**
     * 当前我们自己自定义的全局过滤器执行顺序是 0
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
